package bloomfilter;

import java.util.BitSet;

class SimpleHash {

    public int cap;//当前容量
    public int seed;//随机值

    public SimpleHash(int cap,int seed) {
        this.cap = cap;
        this.seed = seed;
    }

    //根据seed不同 创建不能的哈希函数
    int hash(String key) {
        int h;

        return (key == null) ? 0 : (seed * (cap-1)) & ((h = key.hashCode()) ^ (h >>> 16));
    }

}

public class BloomFilter {
    //默认大小
    public static final int DEFAULT_SIZE = 1 << 20;

    //位图
    public BitSet bitSet;

    //记录存了多少个数据
    public int usedSize;

    public static final int[] seeds = {5,7,11,13,27,33};

    public SimpleHash[] simpleHashes;

    public BloomFilter() {
        bitSet = new BitSet(DEFAULT_SIZE);
        simpleHashes = new SimpleHash[seeds.length];
        for (int i = 0; i < simpleHashes.length; i++) {
            simpleHashes[i] = new SimpleHash(DEFAULT_SIZE,seeds[i]);
        }
    }

    public void set(String val) {
        for (int i = 0; i < simpleHashes.length; i++) {
            int hash = simpleHashes[i].hash(val);
            bitSet.set(hash);
        }
        usedSize++;
    }

    public boolean get(String val) {
        for (int i = 0; i < simpleHashes.length; i++) {
            int hash = simpleHashes[i].hash(val);
            if(!bitSet.get(hash)) {
                return false;
            }
        }
        return true;
    }

    public int size() {
        return usedSize;
    }
}
